package com.faf.ui;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.faf.bean.Access;
import com.faf.bean.Food;
import com.faf.bean.Store;
import com.faf.dao.StoreDao;
import com.faf.dao.impl.AccessDaoImpl;
import com.faf.dao.impl.FoodDaoImpl;
import com.faf.dao.impl.LikesDaoImpl;
import com.faf.dao.impl.StoreDaoImpl;
import com.faf.service.impl.ItemSimilarityImpl;

/**
 * Servlet implementation class Detail
 */
@WebServlet("/Detail")
public class gDetail extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public gDetail() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8"); 
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		String fId = request.getParameter("fid");
		if(null != fId) {
		
		FoodDaoImpl fDao = new FoodDaoImpl();
		LikesDaoImpl lDao = new LikesDaoImpl();

		Food food = null;
		long likecount = 0;
		boolean likeisme = false;
		try {
			food = fDao.getFoodByFoodID(Integer.parseInt(fId));
			likecount = lDao.getLikeNumberByFoodId(food.getFoodId());
			
			if(null != request.getSession().getAttribute("id")) {
				likeisme = lDao.isUserLike((int)request.getSession().getAttribute("id"), food.getFoodId());
			}
		} catch (NumberFormatException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		StoreDaoImpl storeDao = new StoreDaoImpl();
		try {
			Store store = storeDao.getStoreByStoreId(String.valueOf(food.getStoreId()));
			if(null != request.getSession().getAttribute("id")) {
				AccessDaoImpl accessDao = new AccessDaoImpl();
				accessDao.newAccess(store.getStoreId(), food.getFoodId(), (int)request.getSession().getAttribute("id"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		request.setAttribute("likecount", likecount);
		request.setAttribute("likeisme", likeisme);
		request.setAttribute("detail_data_food", null == food ? new Food() : food);
		
		}
		request.getRequestDispatcher("/UserGlobal/detail.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
